<template>
  <div class="training-management">
    <!-- 标题区域 -->
    <div class="page-header">
      <h2>培训报名管理</h2>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-section">
      <el-card>
        <el-form :inline="true" :model="filterForm" class="filter-form">
          <el-form-item label="培训名称">
            <el-input v-model="filterForm.trainingName" placeholder="请输入培训名称"></el-input>
          </el-form-item>
          <el-form-item label="报名状态">
            <el-select v-model="filterForm.status" placeholder="请选择状态">
              <el-option label="全部" value=""></el-option>
              <el-option label="已报名" value="registered"></el-option>
              <el-option label="已确认" value="confirmed"></el-option>
              <el-option label="已完成" value="completed"></el-option>
              <el-option label="已取消" value="cancelled"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="报名日期">
            <el-date-picker
              v-model="filterForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <el-card>
        <el-table :data="registrationList" border stripe v-loading="loading" style="width: 100%">
          <el-table-column prop="trainingName" label="培训名称" min-width="180"></el-table-column>
          <el-table-column prop="employeeName" label="员工姓名" width="120"></el-table-column>
          <el-table-column prop="registerTime" label="报名时间" width="160">
            <template #default="scope">
              {{ formatDate(scope.row.registerTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280" fixed="right">
            <template #default="scope">
              <el-button
                size="small"
                type="primary"
                @click="handleView(scope.row)"
              >查看</el-button>
              <el-button
                size="small"
                type="success"
                v-if="!scope.row.status || scope.row.status === 'cancelled'"
                @click="handleSignUp(scope.row)"
              >报名</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            :page-size="pageSize"
            :current-page="currentPage"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          ></el-pagination>
        </div>
      </el-card>
    </div>

    <!-- 详情对话框 -->
    <el-dialog
      title="报名详情"
      v-model="dialogVisible"
      width="600px"
    >
      <div class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="培训名称">{{ currentDetail.trainingName }}</el-descriptions-item>
          <el-descriptions-item label="员工姓名">{{ currentDetail.employeeName }}</el-descriptions-item>
          <el-descriptions-item label="所属部门">{{ currentDetail.department }}</el-descriptions-item>
          <el-descriptions-item label="报名时间">{{ formatDate(currentDetail.registerTime) }}</el-descriptions-item>
          <el-descriptions-item label="培训时间">{{ currentDetail.trainingTime }}</el-descriptions-item>
          <el-descriptions-item label="培训地点">{{ currentDetail.location }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(currentDetail.status)">
              {{ getStatusText(currentDetail.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="备注">{{ currentDetail.remarks || '-' }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import { API_BASE_URL } from '@/config/api.js'

export default {
  name: 'TrainingManagement',
  data() {
    return {
      filterForm: {
        trainingName: ''
      },
      loading: false,
      registrationList: [],
      total: 0,
      pageSize: 10,
      currentPage: 1,
      dialogVisible: false,
      currentDetail: {}
    }
  },
  methods: {
    // 查询处理
    handleSearch() {
      this.currentPage = 1
      this.fetchData()
    },

    // 重置表单
    resetForm() {
      this.filterForm = {
        trainingName: ''
      }
      this.handleSearch()
    },

    // 获取数据
    async fetchData() {
      this.loading = true;
      try {
        const courseID = this.filterForm.trainingName || '1735133088';
        const response = await fetch(`${API_BASE_URL}/signUpStatusQuery`, {
          method: 'POST',
          credentials: 'include',
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('adminToken')}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ 
            courseID: courseID
          })
        });


        const result = await response.json();

        if (result.code === 0) {
          this.registrationList = result.data.map(item => ({
            trainingName: item.courseName,
            employeeName: item.employeeName,
            employeeID: item.employeeID,
            courseID: item.courseID,
            department: '',
            registerTime: new Date().toISOString(),
            status: this.convertStatus(item.statusCode)
          }));
          console.log('获取课程信息:', result.data, JSON.stringify({ 
            courseID
          }))
          this.total = result.data.length;
        } else {
          throw new Error(result.msg);
        }
      } catch (error) {
        this.$message.error(error.message || '查询失败，请重试或联系开发人员！');
      } finally {
        this.loading = false;
      }
    },

    // 状态码转换方法
    convertStatus(statusCode) {
      const statusMap = {
        0: 'registered',  // 未报名状态显示为已报名
        1: 'confirmed'    // 已报名状态显示为已确认
      };
      return statusMap[statusCode] || 'registered';
    },

    // 状态样式
    getStatusType(status) {
      const statusMap = {
        registered: 'warning',
        confirmed: 'success',
        completed: 'info',
        cancelled: 'danger'
      }
      return statusMap[status]
    },

    // 状态文本
    getStatusText(status) {
      const statusMap = {
        registered: '已报名',
        confirmed: '已确认',
        completed: '已完成',
        cancelled: '已取消'
      }
      return statusMap[status]
    },

    // 查看详情
    handleView(row) {
      this.currentDetail = { ...row }
      this.dialogVisible = true
    },

    // 报名处理
    async handleSignUp(row) {
      try {
        const response = await fetch(`${API_BASE_URL}/courseSignUp`, {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('employeeToken')}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            employeeID: row.employeeID,
            courseID: row.courseID
          })
        });

        const result = await response.json();
        if (result.code === 0) {
          this.$message.success(result.msg);
          this.fetchData();
        } else {
          this.$message.error(result.msg);
        }
      } catch (error) {
        this.$message.error('报名失败，请重试');
      }
    },

    // 分页处理
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchData()
    },

    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()
    },

    // 日期格式化
    formatDate(date) {
      if (!date) return '-'
      return new Date(date).toLocaleDateString()
    },

    // 模拟数据
    mockData() {
      return new Promise(resolve => {
        setTimeout(() => {
          resolve({
            data: [
              {
                id: 1,
                trainingName: '新员工入职培训',
                employeeName: '张三',
                department: '技术部',
                registerTime: '2024-03-15',
                status: 'registered',
                trainingTime: '2024-04-01',
                location: '培训室A',
                remarks: '需要准备笔记本'
              },
              // ���多模拟数据...
            ],
            total: 100
          })
        }, 500)
      })
    }
  },
  created() {
    this.fetchData()
  }
}
</script>

<style scoped>
.training-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  font-size: 24px;
  color: #303133;
  margin: 0;
}

.filter-section {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.table-section {
  background: #fff;
}

.table-operations {
  margin-bottom: 16px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.detail-content {
  padding: 20px;
}

.el-card {
  margin-bottom: 20px;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-table) {
  margin: 16px 0;
}

:deep(.el-tag) {
  text-align: center;
  min-width: 60px;
}
</style>
